package com.cw.jeeyt.controller.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.api.ApiDatabaseDocConfigBo;
import com.cw.jeeyt.service.intf.api.ApiDatabaseDocConfigService;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.common.utils.GsonUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 数据库文档生成配置表控制层
 */
@Controller
@RequestMapping("/apiDatabaseDocConfig")
public class ApiDatabaseDocConfigController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiDatabaseDocConfigController.class);
    @Resource
    private ApiDatabaseDocConfigService apiDatabaseDocConfigService;

    /**
     * 跳转到数据库文档生成配置表列表查询页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDatabaseDocConfig_index");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable datatable数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listApiDatabaseDocConfig")
    public ResultData listApiDatabaseDocConfig(@RequestBody DataTable dataTable) throws Exception {

        ApiDatabaseDocConfigBo apiDatabaseDocConfigBo = GsonUtil.json2Obj(
            GsonUtil.objectToJsonString(dataTable.queryCond), ApiDatabaseDocConfigBo.class);
        if (apiDatabaseDocConfigBo == null) {
            apiDatabaseDocConfigBo = new ApiDatabaseDocConfigBo();
        }
        PageInfo<ApiDatabaseDocConfigBo> pageInfo = apiDatabaseDocConfigService.queryByPage(apiDatabaseDocConfigBo,
            dataTable.getStart(), dataTable.getLength(), dataTable.getOrder()[0]);
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到数据库文档生成配置表表单页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-generateDoc")
    public ModelAndView toGenerateDoc(Long databaseId) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDatabaseDocConfig_generate");
        ApiDatabaseDocConfigBo apiDatabaseDocConfigBo = apiDatabaseDocConfigService.getApiDatabaseDocConfigById(
            databaseId);
        if (apiDatabaseDocConfigBo == null) {
            apiDatabaseDocConfigBo = new ApiDatabaseDocConfigBo();
        }
        apiDatabaseDocConfigBo.setDatabaseId(databaseId);
        mv.addObject("apiDatabaseDocConfig", apiDatabaseDocConfigBo);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 跳转到数据库文档生成配置表表单页面
     *
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDatabaseDocConfig_form");
        ApiDatabaseDocConfigBo apiDatabaseDocConfigBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            apiDatabaseDocConfigBo = new ApiDatabaseDocConfigBo();
        } else {
            apiDatabaseDocConfigBo = apiDatabaseDocConfigService.getApiDatabaseDocConfigById(id);
        }
        mv.addObject("apiDatabaseDocConfig", apiDatabaseDocConfigBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 根据操作类型保存数据库文档生成配置表数据
     *
     * @param apiDatabaseDocConfigBo
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveApiDatabaseDocConfig", method = RequestMethod.POST)
    public JsonResultDto saveApiDatabaseDocConfig(ApiDatabaseDocConfigBo apiDatabaseDocConfigBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            ApiDatabaseDocConfigBo configBo = apiDatabaseDocConfigService.getApiDatabaseDocConfigByDatabaseId(
                apiDatabaseDocConfigBo.getDatabaseId());
            if (configBo == null) {
                apiDatabaseDocConfigService.insert(apiDatabaseDocConfigBo);
            } else {
                apiDatabaseDocConfigService.update(apiDatabaseDocConfigBo);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("databaseId", apiDatabaseDocConfigBo.getDatabaseId());
            jsonResultDto.setResultData(map);
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存数据库文档生成配置表失败", e);
        }
        return jsonResultDto;
    }

    /**
     * 删除数据库文档生成配置表
     *
     * @param apiDatabaseDocConfigBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(ApiDatabaseDocConfigBo apiDatabaseDocConfigBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            apiDatabaseDocConfigService.delete(apiDatabaseDocConfigBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
            logger.error("删除数据库文档生成配置表失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 生成数据库文档
     *
     * @param databaseId
     * @throws Exception
     */
    @RequestMapping(value = "/generateDatabaseDoc")
    @ResponseBody
    public void generateDoc(HttpServletRequest request, HttpServletResponse response, Long databaseId,
        String generateTablePrefix){
        try {
            apiDatabaseDocConfigService.generateDoc(databaseId, generateTablePrefix, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成数据库文档失败：" + e.getMessage());
        }
    }
}
